import { reactive, ref } from 'vue'
import { adapter, request } from '@/request'
import { BwPriceAskWordByPosts } from '@/core/api/priceSheet'
import type { Industry } from '@/core/interfaces/industry'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import type { RequestWrapper } from '@/core/interfaces/common'
import type { ChannelEnum } from '@/core/enums/name'
import { ApproveStatusEnum } from '@/core/enums/status'
import type { PlatformEnum, ProductEnum } from '@/core/enums/platform'
import type { SetOptional } from 'type-fest'
import type { Premium } from '@/core/interfaces/premium'

export interface BwWordAsk extends PriceKeyword {
  channelId: ChannelEnum
  cheapVersionSoldAreas?: string
  standardVersionSoldAreas?: string
}

export interface AssessmentPrice {
  assessmentPrice: number
  clientType: PlatformEnum
  // days: 365 | 180 | 90 | 30
  days: 730 | 365 | 180 | 90 | 30
  onlinePeriodDays: number
  onlinePeriodHours: number
  priceTypeId: number
}

export interface BwPriceAskParams {
  biaowang: ProductEnum
  priceAskWords: string[]
  serviceAreas: string[]
  userAreas: string[]
  assessmentPricesId: number
  comboPriceName?: string
  productId?: ProductEnum
}

export enum FailtureCodeEnum {
  // 单词需人工审核
  ManualReview = -1,
  // 单词已出售
  Sold = -2,
  DisablePC = -3,
  DisableMobile = -4,
  DisablePlatform = -5
}

export interface BwPriceAskWords {
  wordAskWords: BwWordAsk[]
  assessmentPrices: AssessmentPrice[]
  msg: string
  failtureCode?: FailtureCodeEnum
  subjectCode?: Industry['code']
  assessmentPricesId: number
  approveStatus: ApproveStatusEnum
  premiums: Premium[]

  machineExamine?: number
  costRate?: number
}

export default function getBwPriceAskWords() {
  const service = adapter<RequestWrapper<SetOptional<BwPriceAskWords, 'assessmentPrices'>>>(request)
  const loading = ref(false)
  const defaultResponse = () => ({
    wordAskWords: [],
    assessmentPrices: [],
    msg: '',
    assessmentPricesId: 0,
    approveStatus: ApproveStatusEnum.PENDING,
    subjectCode: undefined,
    failtureCode: undefined,
    premiums: [],
    machineExamine: undefined
  })
  const response = reactive<BwPriceAskWords>(defaultResponse())

  const fetch = (data: BwPriceAskParams) => {
    // 这里一定要重置下，不然assessmentPrices字段会有残留，因为本次搜索关键词有报价，但是下次搜索的结果不一定有报价
    Object.assign(response, defaultResponse())
    const { url, method } = BwPriceAskWordByPosts()
    loading.value = true

    return service({
      config: {
        url,
        method,
        data
      },
      callback: (res) => {
        Object.assign(response, res.data.data)
      },
      error: (err) => {
        console.log(err)
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
